package apphttp

import (
	"net/http"
	"html/template"
	"os"
	"io"

	"TanguyWeb/main/bean"
	"TanguyWeb/main/utils"
	"TanguyWeb/main/config"
	"gitee.com/DengAnbang/goutils/loge"
)

func upload(w http.ResponseWriter, r *http.Request) error {
	if r.Method == "GET" {
		t, err := template.ParseFiles(fileutils.ViewRootPath + "upload.html")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return err
		}
		t.Execute(w, nil)
	}
	if r.Method == "POST" {
		f, h, err := r.FormFile("image")
		if err != nil {
			if err == http.ErrMissingFile {
				return bean.NewResultError(config.Err, "文件不能为空!")
			}
			return err
		}
		filename := h.Filename
		defer f.Close()
		t, err := os.Create(fileutils.FileRootPath + filename)
		if err != nil {
			return err
		}
		defer t.Close()
		if _, err := io.Copy(t, f); err != nil {
			return err
		}
		return bean.NewResultData(fileutils.Filename2Url(filename, "file"))
	}
	return nil
}
func viewHandler(w http.ResponseWriter, r *http.Request) error {
	//url := r.URL.Path
	//index := strings.LastIndex(url, "app/file")
	//loge.E(index)

	imagePath := r.FormValue("imagePath")
	loge.E(imagePath)
	if exists := fileutils.PathExists(imagePath); !exists {
		http.NotFound(w, r)
		return nil
	}
	w.Header().Set("Content-Type", "image")
	http.ServeFile(w, r, imagePath)
	return nil
}
